package org.jeecg.access.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.access.constant.PlatformType;
import org.jeecg.access.entity.PlatformAccount;
import org.jeecg.access.platform.entity.*;
import org.jeecg.access.platform.mapper.XhsUserInfoMapper;
import org.jeecg.access.platform.mapper.XhsWorkDataMapper;
import org.jeecg.access.platform.service.PlatformHandler;
import org.jeecg.access.platform.util.HttpRequestUtil;
import org.jeecg.access.platform.util.JsonParserUtils;
import org.jeecg.access.service.PlatformAccountService;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.util.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小红书数据获取服务实现类
 * 统一使用JsonParserUtils解析JSON字符串，HttpRequestUtil发送请求，不使用流式/函数式编程
 */
@Slf4j
@Service
public class XhsGetDataServiceImpl extends AbstractGetDataServiceImpl implements PlatformHandler {

    private final XhsUserInfoMapper userInfoMapper;
    private final XhsWorkDataMapper workDataMapper;

    private final PlatformAccountService platformAccountService;

    @Value("${more.token}")
    private String token;
    @Value("${more.xhs.userDetail}")
    private String userDetailUrl;
    @Value("${more.xhs.userPost}")
    private String userPostUrl;
    @Value("${more.xhs.noteDetail}")
    private String noteDetailUrl;
    @Value("${batch.size:100}")
    private int userBatchSize;
    @Value("${works.batch.size:500}")
    private int worksBatchSize;
    // 最大分页限制
    private static final int MAX_PAGE_LIMIT = 20;

    /**
     * 构造方法：注入依赖并调用父类构造
     */
    @Autowired
    public XhsGetDataServiceImpl(
            XhsUserInfoMapper userInfoMapper,
            XhsWorkDataMapper workDataMapper,
            HttpRequestUtil httpRequestUtil,
            ObjectMapper objectMapper,
            PlatformAccountService platformAccountService
    ) {
        super(httpRequestUtil, objectMapper);
        this.userInfoMapper = userInfoMapper;
        this.workDataMapper = workDataMapper;
        this.platformAccountService = platformAccountService;
    }

    // ========================== 用户信息同步实现 ==========================

    /**
     * 获取小红书用户列表
     */
    @Override
    protected List<? extends BaseUserInfo> fetchUserInfoList() {
        List<XhsUserInfo> userInfos = userInfoMapper.getUserInfos();
        return userInfos != null ? userInfos : new ArrayList<>();
    }

    /**
     * 为单个用户创建请求头
     */
    @Override
    protected Map<String, String> createUserRequestHeaders(BaseUserInfo user) {
        Map<String, String> headers = new HashMap<>(3);
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", token);

        if (user instanceof XhsUserInfo) {
            XhsUserInfo xhsUser = (XhsUserInfo) user;
            String userCookie = xhsUser.getCookie();
            if (userCookie != null && !userCookie.trim().isEmpty()) {
                headers.put("Cookie", userCookie.trim());
                log.debug("用户 {} 已设置Cookie", xhsUser.getUserId());
            }
        } else {
            log.warn("创建用户请求头：用户类型不是XhsUserInfo");
        }
        return headers;
    }

    /**
     * 为单个用户组装请求报文
     */
    @Override
    protected String buildUserRequestData(BaseUserInfo user) {
        if (!(user instanceof XhsUserInfo)) {
            log.error("用户类型错误，无法构建请求报文");
            return "";
        }
        XhsUserInfo xhsUser = (XhsUserInfo) user;
        String userId = xhsUser.getUserId();

        if (userId == null || userId.trim().isEmpty()) {
            log.error("用户ID为空，无法构建请求报文");
            return "";
        }

        Map<String, Object> requestBody = new HashMap<>(2);
        requestBody.put("user_id", userId.trim());
        requestBody.put("proxy", "");

        try {
            return objectMapper.writeValueAsString(requestBody);
        } catch (JsonProcessingException e) {
            log.error("序列化用户请求参数失败", e);
            return "";
        }
    }

    /**
     * 获取用户信息API的URL
     */
    @Override
    protected String getUserApiUrl(BaseUserInfo user) {
        return userDetailUrl;
    }

    /**
     * 获取用户信息的请求方法
     */
    @Override
    protected String getUserRequestMethod() {
        return "POST";
    }

    /**
     * 创建用户信息请求的重试决策器
     * 校验逻辑：使用JsonParserUtils直接解析响应字符串
     */
    @Override
    protected HttpRequestUtil.RetryDecision createUserRetryDecision(BaseUserInfo user) {
        return new XhsUserRetryDecision();
    }

    /**
     * 小红书用户信息重试决策器（使用JsonParserUtils）
     */
    private class XhsUserRetryDecision implements HttpRequestUtil.RetryDecision {
        @Override
        public boolean needRetry(int responseCode, String response) {

            // 3. 核心数据节点校验（使用JsonParserUtils直接解析字符串）
            try {
                Boolean isBusinessSuccess = JsonParserUtils.isSuccess(response);
                if (isBusinessSuccess == null || !isBusinessSuccess) {
                    log.debug("作品请求业务响应失败，需要重试");
                    return true;
                }

                // 校验核心数据节点是否存在且有效
                Boolean isDataValid = JsonParserUtils.isNodeValid(response, "data.response_body.data");
                // 数据节点无效时需要重试
                if (!isDataValid) {
                    log.debug("用户请求核心数据节点(data)无效，需要重试");
                    return true;
                }
            } catch (Exception e) {
                log.error("解析用户响应失败，需要重试", e);
                return true;
            }

            return false;
        }
    }

    /**
     * 从响应报文中解析数据并组装用户信息（使用JsonParserUtils）
     */
    @Override
    protected BaseUserInfo parseUserResponse(BaseUserInfo originalUser, String response) {
        if (!(originalUser instanceof XhsUserInfo)) {
            log.error("用户类型错误，无法解析响应数据");
            return null;
        }
        XhsUserInfo xhsUser = (XhsUserInfo) originalUser;
        String userId = xhsUser.getUserId();

        try {
            // 使用JsonParserUtils直接解析响应字符串
            String nickname = JsonParserUtils.getStringValueFromString(response, "data.response_body.data.basic_info.nickname");
            String desc = JsonParserUtils.getStringValueFromString(response, "data.response_body.data.basic_info.desc");

            xhsUser.setName(nickname != null ? nickname.trim() : "");
            xhsUser.setDescription(desc != null ? desc.trim() : "");

            // 处理互动数据（获取数组长度）
            Integer interactionCount = JsonParserUtils.getListLength(response, "data.response_body.data.interactions");
            if (interactionCount != null && interactionCount > 0) {
                // 循环处理每个互动数据项
                for (int i = 0; i < interactionCount; i++) {
                    String typePath = "data.response_body.data.interactions[" + i + "].type";
                    String countPath = "data.response_body.data.interactions[" + i + "].count";

                    String type = JsonParserUtils.getStringValueFromString(response, typePath);
                    Integer count = JsonParserUtils.getIntValueFromString(response, countPath);

                    if ("follows".equals(type)) {
                        xhsUser.setFollows(count);
                    } else if ("fans".equals(type)) {
                        xhsUser.setFans(count);
                    } else if ("interaction".equals(type)) {
                        xhsUser.setInteraction(count);
                    }
                }
            }

            // 设置更新信息
//            xhsUser.setUpdater("system");
            xhsUser.setUpdateTime(DateTimeUtil.getCurrentTimestamp());

            return xhsUser;
        } catch (Exception e) {
            log.error("解析用户 {} 响应数据失败", userId, e);
            return null;
        }
    }

    /**
     * 批量更新用户信息
     */
    @Override
    protected void batchUpdateUserInfo(List<? extends BaseUserInfo> userInfos) {
        if (userInfos.isEmpty()) {
            log.info("没有需要更新的小红书用户信息");
            return;
        }

        List<XhsUserInfo> xhsUsers = new ArrayList<>(userInfos.size());
        for (int i = 0; i < userInfos.size(); i++) {
            BaseUserInfo user = userInfos.get(i);
            if (user instanceof XhsUserInfo) {
                xhsUsers.add((XhsUserInfo) user);
            } else {
                log.warn("跳过非小红书用户类型的数据，索引：{}", i);
            }
        }

        if (!xhsUsers.isEmpty()) {
            // 分批处理
            for (int i = 0; i < xhsUsers.size(); i += userBatchSize) {
                int end = Math.min(i + userBatchSize, xhsUsers.size());
                List<XhsUserInfo> batch = new ArrayList<>();
                for (int j = i; j < end; j++) {
                    batch.add(xhsUsers.get(j));
                }
                userInfoMapper.batchUpSert(batch);
                log.info("批量更新小红书用户信息，批次 {} - {}，共 {} 条", i, end - 1, batch.size());
            }
            log.info("批量更新小红书用户信息完成，总计 {} 条", xhsUsers.size());
        }
    }

    // ========================== 作品数据同步实现 ==========================

    /**
     * 创建作品数据请求的重试决策器（使用JsonParserUtils）
     */
    @Override
    protected HttpRequestUtil.RetryDecision createWorkRetryDecision(BaseWorkData workData) {
        return new XhsWorkRetryDecision();
    }

    /**
     * 小红书作品重试决策器
     */
    private class XhsWorkRetryDecision implements HttpRequestUtil.RetryDecision {
        @Override
        public boolean needRetry(int responseCode, String response) {

            // 1. 核心数据节点校验（使用JsonParserUtils）
            try {
                Boolean isBusinessSuccess = JsonParserUtils.isSuccess(response);
                if (isBusinessSuccess == null || !isBusinessSuccess) {
                    log.debug("作品请求业务响应失败，需要重试");
                    return true;
                }

                Integer videoData = JsonParserUtils.getListLength(response, "data.response_body.data.notes");
                if (videoData == null || videoData <= 0) {
                    log.debug("作品请求核心节点(data.response_body.data.notes)无效或为空，需要重试");
                    return true;
                }
            } catch (Exception e) {
                log.error("解析作品响应失败，需要重试", e);
                return true;
            }

            return false;
        }
    }

    /**
     * 获取用户的所有作品
     */
    @Override
    protected List<? extends BaseWorkData> fetchUserAllWorks(BaseUserInfo userInfo, String nowTime,Integer dataNum) throws Exception {
        if (!(userInfo instanceof XhsUserInfo)) {
            log.error("用户类型错误，无法获取小红书作品");
            return new ArrayList<>();
        }
        XhsUserInfo xhsUser = (XhsUserInfo) userInfo;
        Map<String, String> headers = createHeaders(userInfo);

        return fetchUserWorks(xhsUser, headers, nowTime,dataNum);
    }

    /**
     * 批量更新作品数据
     */
    @Override
    protected void batchUpdateWorksData(List<? extends BaseWorkData> worksData) {
        if (worksData.isEmpty()) {
            log.info("没有需要更新的小红书作品数据");
            return;
        }

        List<XhsWorkData> xhsWorks = new ArrayList<>(worksData.size());
        for (int i = 0; i < worksData.size(); i++) {
            BaseWorkData work = worksData.get(i);
            if (work instanceof XhsWorkData) {
                xhsWorks.add((XhsWorkData) work);
            } else {
                log.warn("跳过非小红书作品类型的数据，索引：{}", i);
            }
        }

        if (!xhsWorks.isEmpty()) {
            // 分批处理
            for (int i = 0; i < xhsWorks.size(); i += worksBatchSize) {
                int end = Math.min(i + worksBatchSize, xhsWorks.size());
                List<XhsWorkData> batch = new ArrayList<>();
                for (int j = i; j < end; j++) {
                    batch.add(xhsWorks.get(j));
                }
                workDataMapper.batchUpSert(batch);
                log.info("批量更新小红书作品数据，批次 {} - {}，共 {} 条", i, end - 1, batch.size());
            }
            log.info("批量更新小红书作品数据完成，总计 {} 条", xhsWorks.size());
        }
    }

    /**
     * 构造作品相关API的请求头
     */
    @Override
    protected Map<String, String> createHeaders(BaseUserInfo userInfo) {
        Map<String, String> headers = new HashMap<>(2);
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", token);
        if (userInfo instanceof XhsUserInfo) {
            XhsUserInfo xhsUser = (XhsUserInfo) userInfo;
            String userCookie = xhsUser.getCookie();
            if (userCookie != null && !userCookie.trim().isEmpty()) {
                headers.put("Cookie", userCookie.trim());
                log.debug("用户 {} 已设置Cookie", xhsUser.getUserId());
            }
        } else {
            log.warn("创建用户请求头：用户类型不是XhsUserInfo");
        }
        return headers;
    }

    // ========================== 自定义业务方法 ==========================

    /**
     * 获取用户作品列表（分页处理）
     */
    private List<XhsWorkData> fetchUserWorks(XhsUserInfo user, Map<String, String> headers, String nowTime,Integer dataNum) throws IOException {
        String userId = user.getUserId();
        if (userId == null || userId.isEmpty()) {
            log.warn("用户ID为空，无法获取作品");
            return new ArrayList<>();
        }

        List<XhsWorkData> allWorksData = new ArrayList<>();
        String cursor = "";
        int page = 0;
        boolean hasMore = true;

        // 分页获取作品数据
        // 判断是否需要分页处理（条件：dataNum不为空且等于1）
        boolean needPagination = (null != dataNum && dataNum != 1);

        do {
            page++;
            String response = requestUserPostPage(userId, headers, cursor);
            if (response == null) {
                break;
            }

            // 解析分页数据
            PageParseResult parseResult = parseWorksPage(response, user, nowTime);
            if (parseResult.pageData.isEmpty()) {
                hasMore = false;
            } else {
                allWorksData.addAll(parseResult.pageData);  // 使用addAll更高效
                log.info("小红书用户 {} 第{}页获取{}条作品数据",
                        userId, page, parseResult.pageData.size());
            }

            // 更新分页状态
            hasMore = parseResult.hasMore;
            cursor = parseResult.nextCursor;

            // 当不需要分页时，处理完第一页后立即退出
            if (!needPagination) {
                break;
            }

        } while (page < MAX_PAGE_LIMIT && hasMore);

        compensateDetail(user,allWorksData);

        return allWorksData;
    }

    private void compensateDetail(XhsUserInfo userInfo, List<XhsWorkData> workDataList) {
        if (null == userInfo || userInfo.getUserId().isEmpty() ||
                null == workDataList || workDataList.isEmpty()) {
            log.warn("补充作品详情的参数无效，跳过处理");
            return;
        }

        String userId = userInfo.getUserId();
        Map<String, String> headers = createHeaders(userInfo); // 复用请求头构建方法

        // 传统for循环处理作品列表（不使用流式编程）
        for (int i = 0; i < workDataList.size(); i++) {
            XhsWorkData workData = workDataList.get(i);
            if (workData == null) {
                log.warn("用户[{}]的第{}个作品数据为空，跳过", userId, i + 1);
                continue;
            }

            // 获取作品唯一标识
            String noteId = workData.getNoteId();
            String xsecToken = workData.getXsecToken();

            if (noteId == null || xsecToken == null || noteId.isEmpty() || xsecToken.isEmpty()) {
                log.warn("用户[{}]的第{}个作品缺少noteId或者xsecToken，无法补充详情", userId, i + 1);
                continue;
            }

            try {
                // 1. 构建详细数据请求体
                String requestBody = buildDetailRequestBody(noteId,xsecToken);
                if (requestBody.isEmpty()) {
                    log.warn("用户[{}]的第{}个作品请求体构建失败，跳过", userId, i + 1);
                    continue;
                }

                // 2. 发送请求获取详细数据（使用作品重试决策器）
                String response = httpRequestUtil.sendRequest(
                        noteDetailUrl,
                        "POST",
                        headers,
                        requestBody,
                        new WorkDetailRetryDecision()
                );

                // 3. 校验响应有效性
                if (response == null || response.trim().isEmpty()) {
                    log.warn("用户[{}]的第{}个作品详情响应为空，跳过", userId, i + 1);
                    continue;
                }

                // 4. 解析响应并补充作品详情
                parseAndFillDetail(workData, response);

                // 5. 更新最后补充时间
                log.debug("用户[{}]的第{}个作品详情补充完成", userId, i + 1);

            } catch (Exception e) {
                // 单个作品处理失败不影响整体循环
                log.error("用户[{}]的第{}个作品详情补充失败: {}", userId, i + 1, e.getMessage(), e);
            }
        }
    }

    /**
     * 解析详细数据响应并填充到作品对象
     * @param workData 待填充的作品对象
     * @param response 接口响应数据
     */
    private void parseAndFillDetail(XhsWorkData workData, String response) {

        workData.setName(JsonParserUtils.getStringValueFromString(response,"data.response_body.data.items[0].title"));
        workData.setDescription(JsonParserUtils.getStringValueFromString(response,"data.response_body.data.items[0].desc"));
        // 补充点赞数
        workData.setLikedCount(JsonParserUtils.getIntValueFromString(response, "data.response_body.data.items[0].note_card.liked_count"));
        // 补充收藏数
        workData.setCollectedCount(JsonParserUtils.getIntValueFromString(response, "data.response_body.data.items[0].note_card.collected_count"));
        // 补充弹幕数
        workData.setCommentCount(JsonParserUtils.getIntValueFromString(response, "data.response_body.data.items[0].note_card.comment_count"));
        //补充分享数
        workData.setShareCount(JsonParserUtils.getIntValueFromString(response, "data.response_body.data.items[0].note_card.share_count"));

        // 补充发布时间（可能包含更精确的时间戳）
        Long publishTimestamp = JsonParserUtils.getLongValueFromString(response, "data.response_body.data.last_update_time");
        if (null != publishTimestamp && publishTimestamp > 0l) {
            workData.setCreateTime( DateTimeUtil.convertTimestampToFormat(publishTimestamp));
        }
    }

    /**
     * @description: to do
     * @param: noteId
     * @param: xsecToken
     * @return: java.lang.String
     * @author: taogang
     * @date:   2025/8/7 15:12
     */
    private String buildDetailRequestBody(String noteId,String xsecToken) {
        Map<String, String> requestMap = new HashMap<>(4);
        requestMap.put("note_id", noteId);
        requestMap.put("xsec_token", xsecToken);
        requestMap.put("share_text", "");
        requestMap.put("proxy", "");

        try {
            return objectMapper.writeValueAsString(requestMap);
        } catch (JsonProcessingException e) {
            log.error("构建作品详情请求体失败（noteId={}, xsecToken={}）", noteId,xsecToken, e);
            return "";
        }
    }

    /**
     * B站作品重试决策器（增强版）
     * 校验逻辑：
     * 1. HTTP状态码非200时重试
     * 2. 响应中后续需使用的核心数据节点（data.items）无效时重试
     */
    private class WorkDetailRetryDecision implements HttpRequestUtil.RetryDecision {
        @Override
        public boolean needRetry(int responseCode, String response) {
            // 1. HTTP状态码校验
            if (responseCode < 200 || responseCode >= 300) {
                log.debug("作品请求HTTP状态码异常({})，需要重试", responseCode);
                return true;
            }

            // 2. 核心数据节点校验（后续需使用data.videoData节点）
            try {
                Boolean isBusinessSuccess = JsonParserUtils.isSuccess(response);
                if (isBusinessSuccess == null || !isBusinessSuccess) {
                    log.debug("作品请求业务响应失败，需要重试");
                    return true;
                }

                Boolean isDataValid = JsonParserUtils.isNodeValid(response, "data.response_body.data.items");
                if (!isDataValid ) {
                    log.debug("作品请求核心节点(data.response_body.data.items)无效或为空，需要重试");
                    return true;
                }
            } catch (Exception e) {
                log.error("解析作品响应失败，需要重试", e);
                return true;
            }
            return false;
        }
    }


    /**
     * 请求单页作品数据
     */
    private String requestUserPostPage(String userId, Map<String, String> headers, String cursor) throws IOException {
        long startTime = System.currentTimeMillis();

        Map<String, Object> requestBody = new HashMap<>(3);
        requestBody.put("user_id", userId);
        requestBody.put("cursor", cursor);
        requestBody.put("proxy", "");

        String requestJson;
        try {
            requestJson = objectMapper.writeValueAsString(requestBody);
        } catch (Exception e) {
            throw new IOException("序列化作品请求参数失败", e);
        }

        try {
            String response = httpRequestUtil.sendRequest(
                    userPostUrl,
                    "POST",
                    headers,
                    requestJson,
                    createWorkRetryDecision(new XhsWorkData())
            );

            long responseTime = System.currentTimeMillis() - startTime;
            if (response == null || response.trim().isEmpty()) {
                log.warn("小红书用户 {} 作品请求返回空响应，耗时: {}ms", userId, responseTime);
                return null;
            }

            log.info("小红书用户 {} 作品请求完成，响应时间: {}ms", userId, responseTime);
            return response;

        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("小红书用户 {} 请求异常（{}ms）: {}", userId, responseTime, e.getMessage());
            return null;
        }
    }

    /**
     * 解析单页作品数据（使用JsonParserUtils）
     */
    private PageParseResult parseWorksPage(String response, XhsUserInfo user, String nowTime) {
        List<XhsWorkData> resultList = new ArrayList<>();
        boolean hasMore = false;
        String nextCursor = "";

        if (response == null) {
            return new PageParseResult(resultList, hasMore, nextCursor);
        }

        try {
            // 解析分页控制信息
            hasMore = JsonParserUtils.getBooleanValueFromString(response, "data.response_body.data.has_more");
            nextCursor = JsonParserUtils.getStringValueFromString(response, "data.response_body.data.cursor");

            // 获取作品列表长度
            Integer notesCount = JsonParserUtils.getListLength(response, "data.response_body.data.notes");
            if (notesCount == null || notesCount <= 0) {
                log.debug("作品列表为空");
                return new PageParseResult(resultList, hasMore, nextCursor);
            }

            // 循环解析每个作品
            for (int i = 0; i < notesCount; i++) {
                String basePath = "data.response_body.data.notes[" + i + "]";
                XhsWorkData work = new XhsWorkData();

                work.setId(UUIDGenerator.generate());
                work.setUserId(user.getId());
                work.setNoteId(JsonParserUtils.getStringValueFromString(response, basePath + ".note_id"));
                work.setXsecToken(JsonParserUtils.getStringValueFromString(response, basePath + ".xsec_token"));
                work.setName(JsonParserUtils.getStringValueFromString(response, basePath + ".display_title"));
                work.setCreateTime(nowTime);
                work.setUpdateTime(nowTime);

                // 提取互动数据
//                work.setLikedCount(JsonParserUtils.getIntValueFromString(response, basePath + ".interact_info.liked_count"));

                resultList.add(work);
            }
        } catch (Exception e) {
            log.error("解析作品分页数据失败", e);
        }

        return new PageParseResult(resultList, hasMore, nextCursor);
    }

    /**
     * 内部类：封装分页解析结果
     */
    private static class PageParseResult {
        final List<XhsWorkData> pageData;
        final boolean hasMore;
        final String nextCursor;

        PageParseResult(List<XhsWorkData> pageData, boolean hasMore, String nextCursor) {
            this.pageData = pageData != null ? pageData : new ArrayList<>();
            this.hasMore = hasMore;
            this.nextCursor = nextCursor != null ? nextCursor : "";
        }
    }

    // ========================== PlatformHandler接口实现 ==========================

    /**
     * 返回小红书平台类型编码
     */
    @Override
    public String getPlatformType() {
        return PlatformType.REDBOOK.getCode();
    }

    /**
     * 获取本地系统中已有的小红书用户数据
     */
    @Override
    public List<?> fetchExternalData() {
        List<XhsUserInfo> localUserList = userInfoMapper.getUserInfos();
        if (localUserList == null) {
            log.warn("本地小红书用户表查询返回null，返回空列表");
            return new ArrayList<>();
        }
        log.info("从本地小红书用户表获取到 {} 条已有数据", localUserList.size());
        return localUserList;
    }

    /**
     * 从本地用户数据中提取账号唯一标识
     */
    @Override
    public String extractAccountId(Object data) {
        if (data == null || !(data instanceof XhsUserInfo)) {
            log.warn("本地用户数据格式无效，无法提取账号ID");
            return null;
        }
        XhsUserInfo localUser = (XhsUserInfo) data;
        return localUser.getId();
    }

    /**
     * 校验账号有效性（使用JsonParserUtils）
     */
    @Override
    public boolean verifyAccount(PlatformAccount account) {
        if (account == null || account.getAccountId() == null || account.getAccountId().trim().isEmpty()) {
            log.warn("待校验账号信息无效（ID为空）");
            return false;
        }

        String uid = account.getAccountId().trim();
        XhsUserInfo userInfo = new XhsUserInfo();
        userInfo.setUserId(uid);
        userInfo.setCookie(account.getCookie());

        Map<String, String> headers = createUserRequestHeaders(userInfo);

        try {
            String requestBody = buildUserRequestData(userInfo);
            if (requestBody.isEmpty()) {
                log.error("构建账号校验请求报文失败");
                return false;
            }

            String response = httpRequestUtil.sendRequest(
                    getUserApiUrl(userInfo),
                    getUserRequestMethod(),
                    headers,
                    requestBody,
                    createUserRetryDecision(userInfo)
            );

            if (response == null || response.trim().isEmpty()) {
                log.warn("账号[{}]校验失败：响应为空", uid);
                return false;
            }

            log.info("账号[{}]校验成功：在小红书真实存在", uid);
            return true;
        } catch (Exception e) {
            log.error("账号[{}]校验失败：小红书API请求异常", uid, e);
            return false;
        }
    }

    /**
     * 将校验通过的账号同步到本地表
     */
    @Override
    public void writeToExternalSystem(PlatformAccount account) {
        if (account == null || account.getAccountId() == null || account.getAccountId().trim().isEmpty()) {
            log.warn("待同步账号信息无效（ID为空）");
            return;
        }

        String uid = account.getAccountId().trim();
        String nowTime = DateTimeUtil.getCurrentTimestamp();
        XhsUserInfo userInfo = new XhsUserInfo();

        userInfo.setUserId(uid);
        userInfo.setCookie(account.getCookie());
        userInfo.setCreateTime(account.getCreateTime());
        userInfo.setUpdateTime(nowTime);
        userInfo.setState(account.getState());
        userInfo.setId(account.getId());

        userInfoMapper.insert(userInfo);
        log.info("账号[{}]已同步到本地小红书用户表", uid);
    }

    @Override
    public String verifyAddedAccount(PlatformAccount account) {
        if (null == account.getAccountId() || account.getAccountId().trim().isEmpty()) {
            return "小红书账号的appId不能为空";
        }

        QueryWrapper<PlatformAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("platform_type", account.getPlatformType());
        queryWrapper.eq("account_id", account.getAccountId());

        int count = platformAccountService.count(queryWrapper);
        if (count > 0) {
            return "小红书账号的accountId账号已存在";
        }

        return null;
    }
}
